package com.superhero.website.service.impl;

import com.superhero.common.Enum.RoleType;
import com.superhero.common.constant.Constant;
import com.superhero.common.exception.BusinessException;
import com.superhero.common.pojo.entity.AuthUser;
import com.superhero.common.pojo.vo.website.LoginOutput;
import com.superhero.common.repository.AuthUserRepository;
import com.superhero.common.utils.OptionalUtil;
import com.superhero.website.security.JwtTokenUtils;
import com.superhero.website.security.UserUtil;
import com.superhero.website.service.LoginService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author huangguifen <1103378449@qq.com>
 * @date 2020/6/21
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    BCryptPasswordEncoder passwordEncoder;
    @Resource
    JwtTokenUtils jwtTokenUtils;
    @Resource
    AuthUserRepository authUserRepository;

    @Override
    public LoginOutput login(String username, String password) {
        Optional<AuthUser> user = authUserRepository.findAuthUserByUsername(username);
        if (!user.isPresent()) {
            throw new BusinessException("用户不存在");
        }
        boolean isMatch = passwordEncoder.matches(password, user.get().getPassword());
        if (!isMatch) {
            throw new BusinessException("密码错误");
        }
        if (user.get().getLocked().equals(Constant.YES)) {
            throw new BusinessException("您的账号已被锁定，请联系管理员了解详情");
        }
        if (user.get().getRole() != RoleType.ADMIN.ordinal()) {
            throw new BusinessException("您的账号没有管理员权限");
        }
        LoginOutput output = new LoginOutput();
        String token = jwtTokenUtils.generateToken(user.get());
        output.setUsername(user.get().getUsername())
                .setRole(user.get().getRole())
                .setToken(token);
        return output;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changePassword(String oldPassword, String newPassword) {
        String username = UserUtil.getUsername();
        AuthUser authUser = OptionalUtil.get(authUserRepository.findAuthUserByUsername(username));
        boolean isMatch = passwordEncoder.matches(oldPassword, authUser.getPassword());
        if (!isMatch) {
            throw new BusinessException("您输入的旧密码错误！");
        }
        authUser.setPassword(passwordEncoder.encode(newPassword));
        authUserRepository.saveAndFlush(authUser);
    }
}
